<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @package    FeatherCMS
 * @copyright  Copyright (c) 2006, Julien PORTALIER
 * @link       http://portalier.com/feather
 * @license    http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

$filePath = preg_replace('~^/~', '', $_GET['url']);
$resolutions = array(
	'icon'      => 35,
	'square'    => 75,
	'thumbnail' => 100,
	'small'     => 240,
	'medium'    => 500,
	'large'     => 1024
);

if (!file_exists($filePath))
{
	// not found
	header("HTTP/1.1 404 Not Found");
	exit;
}
elseif (!isset($_GET['size']) or !isset($resolutions[$_GET['size']]))
{
	// not asked for a size or asked for a wrong size?
	// let's redirect to original file
	header('HTTP/1.1 301 Moved Permanently');
	header("Location: /$filePath");
	exit;
}

// browser cache (6 hours)
header("Expires: ".gmdate('D, j M Y H:i:s', time() + 3600 * 6)." GMT");
header("Cache-Control: cache");	// HTTP/1.1
header("Pragma: cache");		// HTTP/1.0

// server thumbnail's cache
$fileCache = '../tmp/cache/thumbnails/'.md5($_GET['size'].'-'.$filePath);
$expired   = true;

// checks cache
if (file_exists($fileCache))
{
	$now = time();
	$expires = 3600 * 6;
	
	// has cache expired?
	if (filemtime($fileCache) + ($expires - $now) < $now)
		@unlink($fileCache);
	else
		$expired = false;
}

// need to create cache?
if ($expired)
{
	require '../../feather2/libs/resampler.php';
	$resampler = new Resampler($filePath);
	$max = $resolutions[$_GET['size']];
	$resampler->create($fileCache, $max, $max,
		($_GET['size'] == 'square' or $_GET['size'] == 'icon') ? true : false);
}

// returns thumbnail
header('Content-Type: image/jpeg');
$data = readfile($fileCache);
?>